package com.pinyoumei.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.pinyoumei.base.ResponseResult;
import com.pinyoumei.pojo.TbUser;
import com.pinyoumei.utils.CookieUtils;
import com.pinyoumei.utils.JsonUtils;
import com.pinyoumei.web.fegin.MemberServiceFegin;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class MemberController {

	@Autowired
	private MemberServiceFegin memberServiceFegin;
	
	/**
	 * 注册用户具体业务
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/register/user",method=RequestMethod.POST)
	public String registerPost(TbUser user){
		
		//1. 参数校验
		log.info("user:"+JsonUtils.objectToJson(user));
		//2. feign调用会员注册接口
		String result=memberServiceFegin.registerUser(user);
		log.info("#############调用会员注册接口返回结果:"+result+"##################");
		ResponseResult response=JsonUtils.jsonToPojo(result, ResponseResult.class);
		if(200==response.getCode()){
			return "register_success";
		}
		return "register_fail";
		
	}
	
	/**
	 * 用户登录具体业务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/user/login",method=RequestMethod.POST)
	public String login(HttpServletRequest request,HttpServletResponse response,Model model){
		//首先获取cookie,若能获取cookie,直接从Redis中获取用户,直接返回
		String token=CookieUtils.getCookieValue(request, "TT_TOKEN");
		log.info("#############客户端token:"+token+"##################");
		//token有值
		if(!StringUtils.isEmpty(token)){
			String userJsonStr=memberServiceFegin.getUserByTokenFromRedis(token);
			if(!StringUtils.isEmpty(userJsonStr)){
				model.addAttribute("user", userJsonStr);
				return "login_success";
			}
		}
		//1.获取参数
		String userName=request.getParameter("userName");
		String password=request.getParameter("password");
		//2.参数校验
		log.info("#############会员登录接收参数userName:"+userName+"   password:"+password+"##################");
		//3. feign调用会员注册接口,先从cookie中获取token,再从redis查用户信息.如果能查到直接返回,查询不到再查库,写redis和cookie
		String result=memberServiceFegin.login(userName,password);
		log.info("#############调用会员登录接口返回结果:"+result+"##################");
		ResponseResult res=JsonUtils.jsonToPojo(result, ResponseResult.class);
		//获取返回token,写回浏览器
		String userToken=(String) res.getData();
		CookieUtils.setCookie(request, response, "TT_TOKEN", userToken, 60*60*24*14);
		if(200==res.getCode()){
			return "login_success";
		}
		return "login_fail";
	}
}
